package cn.jbit.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/8
 */
public class AcceptCompletionHandler implements CompletionHandler {

    //result为接收事件处理后的对象，即客户端对象
    @Override
    public void completed(Object result, Object attachment) {
        //继续注册一个接收连接的回调函数，形成循环
        ((AioServerHandler)attachment).socketChannel.accept(attachment,this);
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        ((AsynchronousSocketChannel)result).read(byteBuffer,byteBuffer,new ReadCompletionHandler((AsynchronousSocketChannel) result));
    }

    @Override
    public void failed(Throwable exc, Object attachment) {
        exc.printStackTrace();
        ((AioServerHandler)attachment).countDownLatch.countDown();
    }
}
